package com.ncmmall.mall.controller.business.order;

import com.ncmmall.application.business.order.BillLadingApplication;
import com.ncmmall.application.util.code.QRCodeFactory;
import com.ncmmall.domain.business.cloudstore.CloudStoreGoods;
import com.ncmmall.domain.business.order.lading.BillOfLading;
import com.ncmmall.domain.business.order.lading.BillOfLadingRepository;
import com.ncmmall.domain.business.order.lading.QBillOfLading;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.mall.params.PageParams;
import com.ncmmall.mall.utils.wechat.WechatPay;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 提货单管理
 *
 * @author linxs
 * @date 2020-04-29 23:45
 */
@Controller
@RequestMapping(value = "/merchant/billLading")
public class MerchantBillLadingController {

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private BillLadingApplication billLadingApplication;

    @Autowired
    private BillOfLadingRepository billOfLadingRepository;

    /**
     * 列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model, PageParams pageParams, BillOfLading merchant) {
        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo());
        Map<String, Object> params = Maps.newHashMap();
        params.put("id", Securitys.currentUser().getId());

        String hql = builderSQL("select b from BillOfLading b where  b.merchant.id = :id  ", params, merchant);
        QueryPage<BillOfLading> page = queryChannelService.findPage(hql, pageRequest.setParams(params), BillOfLading.class);

        model.addAttribute("page", page).addAttribute("params", merchant);

        return "merchant/billLading/list";
    }

    /**
     * 查看明细
     */
    @RequestMapping(value = "/details", method = RequestMethod.GET)
    public String details(Model model, @RequestParam("id") long id) {

        model.addAttribute("billLading", queryChannelService.findOne(QBillOfLading.billOfLading.id.eq(id), BillOfLading.class));

        return "merchant/billLading/details";
    }

    /**
     * 去支付
     */
    @RequestMapping(value = "/{id}/pay", method = RequestMethod.GET)
    public String pay(Model model, @PathVariable("id") long id) throws Exception {

        BillOfLading billOfLading = queryChannelService.findOne(QBillOfLading.billOfLading.id.eq(id), BillOfLading.class);

        String outTradeNo = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + billOfLading.getMerchant().getId() + billOfLading.getId();

        billOfLading.setPayNo(outTradeNo);
        billOfLadingRepository.save(billOfLading);

        String qrcodeUrl = new WechatPay().mpCodeOrder(billOfLading.getId() + "", outTradeNo, billOfLading.getPrice(), "提货单运费");

        model.addAttribute("url", QRCodeFactory.creatQrImage(qrcodeUrl, 300, 300));
        model.addAttribute("price", billOfLading.getPrice());
        model.addAttribute("id", billOfLading.getId());

        return "merchant/billLading/pay";
    }


    /**
     * 支付结果
     */
    @RequestMapping(value = "/{id}/payResult", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> payResult(@PathVariable("id") long id) {
        BillOfLading billOfLading = queryChannelService.findOne(QBillOfLading.billOfLading.id.eq(id), BillOfLading.class);
        return ImmutableMap.of("status", billOfLading.getPayStatus());
    }


    /**
     * 提货
     */
    @RequestMapping(value = "/{id}/bill", method = RequestMethod.GET)
    public String bill(Model model, @PathVariable("id") long id) {
        Map<String, Object> params = Maps.newHashMap();
        params.put("mid", Securitys.currentUser().getId());
        params.put("id", id);

        String hql = "select d from CloudStoreGoods d where d.merchant.id = :mid and d.supplier.id = :id and d.status = 1 ";
        List<CloudStoreGoods> details = queryChannelService.findAll(hql, params, CloudStoreGoods.class);

        model.addAttribute("details", details).addAttribute("supplierId", id).addAttribute("billLading", new BillOfLading()).addAttribute("_method", "POST");

        return "merchant/billLading/bill";
    }

    /**
     * 发起提货单
     */
    @RequestMapping(value = "/{id}/bill", method = RequestMethod.POST)
    @ResponseBody
    public Map bill(BillOfLading billOfLading) {
        try {

            billOfLading.setMerchant(Securitys.currentUser());
            billLadingApplication.create(billOfLading);

            return ImmutableMap.of("status", true);

        } catch (Exception e) {

            return ImmutableMap.of("status", false);
        }
    }

    /**
     * 签收
     */
    @RequestMapping(value = "/finish", method = RequestMethod.PUT)
    @ResponseBody
    public Map finish(BillOfLading params) {
        try {

            BillOfLading billOfLading = queryChannelService.findOne(QBillOfLading.billOfLading.id.eq(params.getId()), BillOfLading.class);

            billLadingApplication.finish(billOfLading);

            return ImmutableMap.of("status", true);

        } catch (Exception e) {

            return ImmutableMap.of("status", false);
        }
    }

    private String builderSQL(String sql, Map<String, Object> params, BillOfLading merchant) {

        if (StringUtils.isNotBlank(merchant.getOrderNo())) {
            sql += " and b.orderNo = :orderNo";
            params.put("orderNo", merchant.getOrderNo());
        }

        if (StringUtils.isNotBlank(merchant.getOrderNo())) {
            sql += " and b.deliveryName like :deliveryName";
            params.put("deliveryName", "%" + merchant.getDeliveryName() + "%");
        }

        if (StringUtils.isNotBlank(merchant.getDeliveryMobile())) {
            sql += " and b.deliveryMobile = :deliveryMobile";
            params.put("deliveryMobile", merchant.getDeliveryMobile());
        }

        sql += " order by b.createTime desc";
        return sql;
    }

}
